<template>
    <div class="tabsItemBox" v-loading="loading">
        <div class="selftTableBtn">
            <el-button
                size="mini"
                type="primary"
                @click="syncDialogVisible = true"
                >同步</el-button
            >
        </div>

        <div class="classTableBox">
            <div class="classTableBoxTr">
                <div
                    v-for="(item, index) in 7"
                    class="classtableitemTitle"
                    :key="index"
                >
                    周{{ weekVaule[index] }}
                </div>
            </div>
            <div class="classTableBoxTr">
                <div
                    v-for="(l, dayIndex) in showTableList"
                    :key="dayIndex"
                    style="width: 13.8%;"
                >
                    <!-- min-width: 155px; -->
                    <div
                        v-for="(i, index) in lessonList"
                        class="classtableitem"
                        :key="index"
                        :style="[
                            {
                                background: l[index].isNow ? '#19da62' : ''
                            },
                            { color: l[index].isNow ? '#FFF' : '#9FA3B0' }
                        ]"
                    >
                        <div>
                            ({{ i.lesson_start | toGetTime }}~{{
                                i.lesson_end | toGetTime
                            }})
                        </div>
                        <div
                            class="startImg"
                            @click="addDetailsView(l[index], i, dayIndex)"
                        >
                            <div class="noStarImg"></div>
                        </div>
                        <div class="thisClassName">
                            {{ l[index].subject_name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- //弹窗 -->
        <el-dialog title="设置课程" :visible.sync="dialogVisible" width="30%">
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="课程名称" prop="subject_name">
                    <el-input
                        placeholder="请输入课程名称"
                        v-model="form.subject_name"
                    ></el-input>
                </el-form-item>
                <el-form-item label="课程备注">
                    <el-input
                        placeholder="请输入课程备注"
                        v-model="form.remark"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button
                    type="danger"
                    @click="delCourse"
                    v-if="courseItem.unid"
                    >删 除</el-button
                >
                <el-button type="primary" @click="addCourse('ruleForm')" v-else
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <!-- 同步 -->
        <el-dialog
            title="选择同步"
            :visible.sync="syncDialogVisible"
            width="30%"
        >
            <el-checkbox-group v-model="checkList">
                <div v-for="item in weekDataList" :key="item.unid">
                    <el-checkbox :label="item.unid">
                        <div class="selectWeek">
                            <div class="weekName">{{ item.week_name }}</div>
                            <div>({{ item.week_start }} ~</div>
                            <div>~ {{ item.week_end }})</div>
                        </div>
                    </el-checkbox>
                    <el-divider></el-divider>
                </div>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
                <el-button @click="syncDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="asynTable">同 步</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getPersonWeekList,
    getPersonLessonTime,
    getStuScheduleCourse,
    saveStuScheduleCourse,
    delStuScheduleCourse,
    saveStuScheduleWeek
} from "@/api/table";

export default {
    props: ["scheduleItem"],
    watch: {
        scheduleItem: {
            handler(value) {
                this.loading = true;
                console.log("数据", value);
                this.week();
            },
            immediate: true
        }
    },
    data() {
        return {
            weekVaule: ["一", "二", "三", "四", "五", "六", "日"], //星期显示
            weekDataList: [], //周次
            lessonList: [], //时间列表
            showTableList: [], //渲染课表
            loading: false,
            dialogVisible: false,
            form: {
                subject_name: "",
                remark: ""
            },
            //添加课程
            courseItem: {}, //课程详情
            leTimeItem: {}, //时间区间
            dayIndex: 0, //周几
            syncDialogVisible: false,
            checkList: [], //选择同步
            //验证
            rules: {
                subject_name: [
                    {
                        required: true,
                        message: "请输入课程名称",
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    filters: {
        trDate: function(value) {
            value = value.split("-");
            return value[1] + "." + value[2];
        },
        toGetTime: function(value) {
            value = value.split(":");
            return value[0] + ":" + value[1];
        }
    },
    methods: {
        //获取周列表
        async week() {
            var listData;
            /**
             * 获取自订周列表
             */
            var personWeekData = await getPersonWeekList({
                semester_id: this.scheduleItem.semester_id
            });
            listData = personWeekData.data;
            this.weekDataList = listData;
            console.log("获取周列表", listData);
            this.PersonLessonTime();
        },
        //获取时间段
        async PersonLessonTime() {
            var personLessonData = await getPersonLessonTime({
                time_main_id: this.scheduleItem.time_main_id
            });

            var lessonListData = personLessonData.data.list;

            this.lessonList = lessonListData;
            console.log("获取时间段", personLessonData);
            this.StuScheduleCourse();
        },
        //获取课表
        async StuScheduleCourse() {
            var list = await getStuScheduleCourse({
                schedule_id: this.scheduleItem.unid
            });
            this.course = list.data;
            console.log("获取课表", list);
            this.get_week_class_info();
        },
        //获取课表
        get_week_class_info() {
            /**
             * 先找周，有开始时间，结束时间，动态计算出周一到周日对应的日期
             * 找课表，拿取期中一个的time_main_id获取到课节对应时间
             * 课节的uid对应课表的time_lesson_id，day对应周几
             * 最后动态算出课表位置，生成课表
             *
             * 再获取本周签到记录判断用户状态
             */
            var showTableData = [];
            let classInfoArr = this.course;
            var lessonInfoList = this.lessonList;
            //第一次筛选，同一天课程数据集合，一共7天
            for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
                let arr = [];
                classInfoArr.forEach(classEl => {
                    if (classEl.day === dayIndex + 1) {
                        arr.push(classEl);
                    }
                });
                showTableData.push(arr);
            }
            //第二次筛选，排序
            showTableData.forEach((el, index) => {
                //一天有{ lessonInfoList.length } 个时间段，初始填充为{}
                var arr = new Array(lessonInfoList.length).fill({});
                lessonInfoList.forEach((lessonEl, lessonIndex) => {
                    //每天的课排序
                    el.forEach(item => {
                        if (item.time_lesson_id === lessonEl.unid) {
                            arr[lessonIndex] = item;
                        }
                    });
                });
                showTableData[index] = arr;
            });
            console.log("====================================");
            console.log("最终课表：", showTableData);
            console.log("====================================");
            this.showTableList = showTableData;
            //
            this.loading = false;
        },
        addDetailsView(item, item2, dayIndex) {
            this.form = {
                subject_name: "",
                remark: ""
            };
            this.dialogVisible = true;
            this.courseItem = item;
            this.leTimeItem = item2;
            this.dayIndex = dayIndex;
            if (item.unid) {
                this.form = {
                    subject_name: item.subject_name,
                    remark: item.remark
                };
            }
            console.log(item, item2, dayIndex);
        },
        addCourse(formName) {
            this.$refs[formName].validate(async valid => {
                if (valid) {
                    var query = {
                        ...this.form,
                        schedule_id: this.scheduleItem.unid,
                        day: this.dayIndex + 1,
                        time_lesson_id: this.leTimeItem.unid
                    };
                    var list = await saveStuScheduleCourse(query);
                    console.log("新增课程：", list);
                    if (list.code == 200) {
                        this.$message({
                            type: "success",
                            customClass: "customClass",
                            message: "新增成功!"
                        });
                        this.StuScheduleCourse();
                        this.dialogVisible = false;
                    } else {
                        this.$message.error(list.message);
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        delCourse() {
            this.$confirm("此操作将删除该课程, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    var query = {
                        unid: this.courseItem.unid
                    };
                    var list = await delStuScheduleCourse(query);
                    if (list.code == 200) {
                        this.$message({
                            type: "success",
                            customClass: "customClass",
                            message: "删除成功!"
                        });
                        this.StuScheduleCourse();
                        this.dialogVisible = false;
                    } else {
                        this.$message.error(list.message);
                    }
                })
                .catch(() => {});
        },
        async asynTable() {
            if (this.checkList.length == 0) {
                return this.$message.error("请选择周次");
            }
            var str = this.checkList.join(",");
            var query = {
                semester_week_id: str,
                semester_id: this.scheduleItem.semester_id,
                schedule_id: this.scheduleItem.unid,
                usr_id: this.$store.getters.userInfo.id
            };
            var list = await saveStuScheduleWeek(query);
            console.log("同步", list);
            if (list.code == 200) {
                this.$message({
                    type: "success",
                    customClass: "customClass",
                    message: "同步成功!"
                });
                this.syncDialogVisible = false;
            } else {
                this.$message.error(list.message);
            }
        }
    }
};
</script>

<style scoped lang="scss">
.tabsItemBox {
    width: 100%;
    // height: 830px;
    background-color: #ffffff;
    border-radius: 8px;
    margin-top: 15px;
    box-sizing: border-box;
}

.classTableBox {
    width: 100%;
    margin-top: 27px;

    .classTableBoxTr {
        width: 100%;
        display: flex;
        justify-content: space-around;
    }

    .classtableitemTitle {
        width: 13.8%;
        // min-width: 156.58px;
        text-align: center;
        color: #333;
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 10px;
        .titleDate {
            font-size: 13px;
            font-weight: normal;
            color: #9fa3b0;
        }
    }

    .classtableitem {
        width: 100%;
        // min-width: 155px;
        height: 110px;
        text-align: center;
        color: #9fa3b0;
        border-radius: 8px;
        margin-bottom: 8px;
        font-size: 12px;
        overflow: hidden;
        background: #f4fdff;
        background-size: 100% 100%;
        padding: 7px;
        box-sizing: border-box;
    }

    .thisClassName {
        font-size: 16px;
    }

    .startImg {
        width: 31px;
        height: 31px;
        margin: 4px auto;
        padding-top: 11px;
        cursor: pointer;
        box-sizing: border-box;
    }

    .noStarImg {
        width: 9px;
        height: 9px;
        background: #dadfe6;
        border-radius: 50%;
        margin: 0 auto;
    }
}

.selftTableBtn {
    width: 100%;
    text-align: right;
}

.selectWeek {
    display: flex;
    font-size: 15px;
    color: #9fa3b0;

    .weekName {
        font-weight: 600;
        margin-right: 12px;
        color: #333;
    }
}
</style>
